package com.sh.healthtv.ui;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Chronometer;
import android.widget.Chronometer.OnChronometerTickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.sh.healthtv.R;
import com.sh.healthtv.app.com.sh.healthtv.obserservice.PlayObserveble;
import com.sh.healthtv.config.Constant;
import com.sh.healthtv.net.entity.MediaPlayList;
import com.sh.healthtv.net.service.envelop.PolyManager;
import com.sh.healthtv.view.CommonDialog;
import com.sh.healthtv.view.MarqueeText;
import com.sh.healthtv.view.MyVideoView;
import com.sh.healthtv.view.OperateVideoView;

import rx.Subscriber;


public class EpgPlayer extends BaseFragment {

    private static final String TAG = "YG";
    private View layout;

    private OperateVideoView videoView;

    private boolean isShow = false;

    ImageButton playB;

    SeekBar seekB;

    Chronometer startTime;

    Chronometer endTime;

    // private TextView titleName;
    private MarqueeText epgName;

    private TextView cm_playcontrol_starttime_tv;
    private TextView cm_playcontrol_endtime_tv;
    protected PolyManager mPolyManager;
    private boolean isFirstCreatforResume = false;

    // private View brotherFocusView;
    private int speedSeekTime = 20;
    private int rewSeekTime = 15;

    private RelativeLayout play_epg_top, play_epg_bottom;

    private RelativeLayout mProgressBar;

    // private MediaPlayer mMediaPlayer;
    // private int mUpdateInt;
    // private int lastUpdateInt;
    private boolean isUserPause;

    private ImageView epg_control_bottom_pause;

    private ImageView epg_bg;

    private boolean isPlaying;

    private TextView pop_playTime;

    private PopupWindow pop;
    private int popLowerY;
    private Subscriber<MediaPlayList> mSubscriber;

    private boolean istimestop = true;
    private Boolean net = true;
    // 计算节目暂停了多长时间
    private long pause_duration = 0;
    // 进入时刻
    private long currentHealth = 0;
    // 暂停时刻
    private long pause_time = 0;
    private LinearLayout lincon; //收藏页面
    private ImageView connect_logo;
    private TextView connect_text;
    private MediaPlayList program;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        layout = inflater.inflate(R.layout.play_epg_control, null);
        mPolyManager = PolyManager.getInstence();
        epgName = (MarqueeText) layout
                .findViewById(R.id.tv_player_playforepg_control_epg);
        epg_bg = (ImageView) layout.findViewById(R.id.epg_bg);
        epg_control_bottom_pause = (ImageView) layout
                .findViewById(R.id.epg_control_bottom_pause);
        mProgressBar = (RelativeLayout) layout
                .findViewById(R.id.pb_epgplayer_progress);
        this.videoView = OperateVideoView.getInstance();
        this.mContext = getActivity();
        videoView.registeResever(getActivity());
        initPlayControlLogic();
        makeFocus(playB);
        // handler.sendEmptyMessage(QUERY_COLLECT);

        pop_playTime = (TextView) inflater.inflate(R.layout.video_show_time,
                null);
        pop = new PopupWindow(pop_playTime, LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);

        popLowerY = 90;
        videoView.setListener(false, new MyVideoView.VideoStateListener() {

            @Override
            public void OnUpcoming(boolean isGetNextEpg) {
                /*
                 * if(isGetNextEpg){ if(nextPlayEpg == null){
				 * EpgManagerHelper.getInstance(getActivity()).getNextEpg(
				 * readyPlayTv,redayPlayEpg,epgdate,playHandler); } } else{
				 * handler.removeMessages(CLOSE_MSGV); }
				 */
            }

            @Override
            public void OnSeekBarChange(int progress) {
                seekB.setProgress(progress / 1000);
                startTime.setBase(SystemClock.elapsedRealtime() - progress);
            }

            @Override
            public void OnPrepared(MediaPlayer mp) {

                initcontrol(mp);
                // epg_bg.setVisibility(View.GONE);
                // closeMsg();
                currentHealth = System.currentTimeMillis();
                String sWT = DateFormat.format("yyyy-MM-dd HH:mm:ss", currentHealth).toString();
                isUserPause = true;
                if (!changeurl) {
                    pauseForFirst();
                } else {
                    videoView.pause();
                }
                mProgressBar.setVisibility(View.INVISIBLE);
                isPlayCompletion = false;
                if (plays) {
                    plays = false;
                    isUserPause = false;
                    playvideo();
                    handler.sendEmptyMessage(BREAKPOINT_START_VIDEO);
                } else {
                    if (pauseTime > 0) {
                        if ((pauseTime / 1000 + 10) >= (mp.getDuration() / 1000)) {
                            playvideo();
                            isUserPause = false;
                            handler.sendEmptyMessageDelayed(
                                    CHECK_AND_SET_VIDEO_PROGRESS, 100);
                        } else {
                            if (changeurl) {
                                changeurl = false;
                                handler.sendEmptyMessage(BREAKPOINT_START_VIDEO);
                            } else {
                                playvideo();
                                handler.sendEmptyMessage(BREAKPOINT_START_VIDEO);
                                playB.requestFocus();
                                // handler.sendEmptyMessageDelayed(BREAKPOINT_START_VIDEO,
                                // 100);
                            }

                        }
                    } else {
                        playvideo();
                        isUserPause = false;
                        handler.sendEmptyMessageDelayed(
                                CHECK_AND_SET_VIDEO_PROGRESS, 100);
                    }
                }
            }

            @Override
            public void OnNetWorkChange(boolean isConnect) {
                Log.d(TAG, "网络状态" + isConnect);
                if (isConnect) {
                    net = true;
                } else {
                    net = false;
                    showMsg("无法连接网络，请检查网络是否正常。", 2, true);
                }
            }

            @Override
            public void OnError(MediaPlayer mp, int what, int extra) {
                epg_control_bottom_pause.setVisibility(View.VISIBLE);
                showMsg("该节目暂时无法播放，去看看其他节目吧。", 2, true);
                reset();
                stopPlay();
                startTime.stop();
                mProgressBar.setVisibility(View.INVISIBLE);
                error();
            }

            @Override
            public void OnComPletion(MediaPlayer mp) {
                handler.removeMessages(PLAYERROR);
                isPlayCompletion = true;
                if (mp != null) {
                    int duration = mp.getDuration();
                    startTime.stop();
                    // pauseTime = 0;
                    if (seekB != null) {
                        seekB.setProgress(duration / 1000);
                    }
                }
                epg_control_bottom_pause.setBackgroundDrawable(getActivity()
                        .getResources()
                        .getDrawable(R.mipmap.player_control_play));
                epg_control_bottom_pause.setVisibility(View.VISIBLE);
                // 设置进度条的主要进度，表示当前的播放时间
                //isPlaying = false;
                if (isPlaying) {
                    exitPlayer();
                }
            }

            @Override
            public void OnBufferingStart() {
                handler.removeMessages(DELAYPLAY);
                mProgressBar.setVisibility(View.VISIBLE);
                handler.sendEmptyMessage(VIDEO_IS_BUFFERING);
                if (net) {
                    handler.sendEmptyMessageDelayed(DELAYPLAY, 15000);
                    handler.sendEmptyMessageDelayed(PLAYERROR, 35000);
                }
            }

            @Override
            public void OnBufferingEnd() {
                handler.removeMessages(PLAYERROR);
                handler.removeMessages(DELAYPLAY);
                mProgressBar.setVisibility(View.INVISIBLE);
                handler.sendEmptyMessage(VIDEO_IS_PLAY);
            }
        });

        isFirstCreatforResume = true;

        handler.sendEmptyMessageDelayed(FIRST_PLAY, 30);
        closeMsg();
        return layout;
    }

	/*
     * private void setVideoProgress(MediaPlayer mp) { if(videoView.isPlaying()
	 * && isShow){ int currentPosition, duration; // 获得当前播放时间和当前视频的长度
	 * currentPosition = videoView.getCurrentPosition(); duration =
	 * videoView.getDuration(); int time = ((currentPosition * 100) / duration);
	 * Log.i("pauseTime", "setVideoProgress()   pauseTime:"+time); //
	 * 设置进度条的主要进度，表示当前的播放时间 if(seekB != null){ seekB.setProgress(time); }
	 * startTime.setBase(SystemClock.elapsedRealtime() - currentPosition); //
	 * 设置进度条的次要进度，表示视频的缓冲进度 // seekBar.setSecondaryProgress(percent); }else {
	 * pause(); } // lastUpdateInt = 0; isUserPause = false; videoDuration =
	 * mp.getDuration(); videoCurrentPosition = 0; isinit = false; if(mp ==
	 * null) { return; } mMediaPlayer = mp;
	 * mMediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener()
	 * {
	 * 
	 * @Override public void onBufferingUpdate(MediaPlayer mp, int percent) {
	 * mUpdateInt = percent; Log.i("Main", "UpdateListener  :"+percent); } }); }
	 */

    private boolean isOnePercent = true; // 加载到百分之一后才开始拖动

    @Override
    public void onResume() {
        if (isFirstCreatforResume) {
            /*
             * if(brotherFocusView != null){ makeFocus(brotherFocusView); }
			 */
            isFirstCreatforResume = false;
        }
        super.onResume();
    }

    private Context mContext;

    public EpgPlayer() {
        super();

    }

    private int seekKeySleepTime = 500;

    private boolean isSeekTo;

    private void initPlayControlLogic() {

        play_epg_top = (RelativeLayout) layout.findViewById(R.id.play_epg_top);
        play_epg_bottom = (RelativeLayout) layout
                .findViewById(R.id.play_epg_bottom);

        playB = (ImageButton) layout
                .findViewById(R.id.ib_player_playforepg_control_play);
        seekB = (SeekBar) layout
                .findViewById(R.id.seek_player_playforepg_control_seek);
        seekB.setPadding(0, 0, 0, 0);
        seekB.setMax(0);
        isSeekTo = true;
        lincon = (LinearLayout) layout.findViewById(R.id.lin_con);
        connect_logo = (ImageView) layout.findViewById(R.id.connect_logo);
        connect_text = (TextView) layout.findViewById(R.id.connect_text);
        startTime = (Chronometer) layout
                .findViewById(R.id.cm_playcontrol_starttime);
        endTime = (Chronometer) layout
                .findViewById(R.id.cm_playcontrol_endtime);
        cm_playcontrol_starttime_tv = (TextView) layout
                .findViewById(R.id.cm_playcontrol_starttime_tv);
        cm_playcontrol_endtime_tv = (TextView) layout
                .findViewById(R.id.cm_playcontrol_endtime_tv);

        startTime.stop();
        endTime.stop();

        playB.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    handler.removeMessages(CLOSE_MSGV);
                    handler.removeMessages(CLOSE_MSGV2);
                    handler.sendEmptyMessageDelayed(CLOSE_MSGV, 2500);
                    switch (keyCode) {
                        case Constant.Control_KEYCODE_LEFT:
                            if (!isShow) {
                                showMsg();
                            }
                            // if (is_playing_ad) {
                            // return true;
                            // }
                            if (!isOnePercent) {
                                break;
                            }
                            // mUpdateInt = 0;//
                            // 在快退时，因为先前的缓冲百分比大，所以加载条会消失。为0，让它不消失。
                            if (isShow && seekB.getMax() > 0) {
                                /*
                                 * if ((seekB.getSecondaryProgress() - seekTime)
								 * < 0) { break; }
								 */
                                handler.removeMessages(START_VIDEO);

                                if (isSeekTo) {
                                    isSeekTo = false;
                                    if ((seekB.getProgress() - rewSeekTime) < 0) {
                                        seekB.setSecondaryProgress(0);
                                    } else {
                                        seekB.setSecondaryProgress(seekB
                                                .getProgress() - rewSeekTime);
                                    }
                                    setPop(getDrationTime(seekB.getProgress()),
                                            seekB, seekB.getProgress());
                                } else {
                                    if ((seekB.getSecondaryProgress() - rewSeekTime) < 0) {
                                        seekB.setSecondaryProgress(0);
                                    } else {
                                        seekB.setSecondaryProgress(seekB
                                                .getSecondaryProgress()
                                                - rewSeekTime);
                                    }
                                }
                                updatePop(getDrationTime(seekB
                                        .getSecondaryProgress()), seekB, seekB
                                        .getSecondaryProgress());
                                // pause();
                                // startTime.setBase(SystemClock.elapsedRealtime()
                                // -
                                // pauseTime);
                                // videoView.seekTo(seekB.getProgress() * 1000);

                                handler.sendEmptyMessageDelayed(START_VIDEO,
                                        seekKeySleepTime);
                            }
                            return true;
                        case Constant.Control_KEYCODE_RIGHT:
                            if (!isShow) {
                                showMsg();
                            }
                            // if (is_playing_ad) {
                            // return true;
                            // }
                            if (!isOnePercent) {
                                break;
                            }
                            if (isShow && seekB.getMax() > 0) {

								/*
                                 * if ((seekB.getSecondaryProgress() + seekTime)
								 * > seekB.getMax()) { break; }
								 */
                                handler.removeMessages(START_VIDEO);

                                if (isSeekTo) {
                                    isSeekTo = false;
                                    if ((seekB.getProgress() + speedSeekTime) > seekB
                                            .getMax()) {
                                        seekB.setSecondaryProgress(seekB
                                                .getMax());
                                    } else {
                                        seekB.setSecondaryProgress(seekB
                                                .getProgress() + speedSeekTime);
                                    }
                                    setPop(getDrationTime(seekB.getProgress()),
                                            seekB, seekB.getProgress());
                                } else {
                                    if ((seekB.getSecondaryProgress() + speedSeekTime) > seekB
                                            .getMax()) {
                                        seekB.setSecondaryProgress(seekB
                                                .getMax());
                                    } else {
                                        seekB.setSecondaryProgress(seekB
                                                .getSecondaryProgress()
                                                + speedSeekTime);
                                    }
                                }
                                updatePop(getDrationTime(seekB
                                        .getSecondaryProgress()), seekB, seekB
                                        .getSecondaryProgress());
                                // pause();
                                // startTime.setBase(SystemClock.elapsedRealtime()
                                // -
                                // pauseTime);
                                // videoView.seekTo(seekB.getProgress() * 1000);

                                handler.sendEmptyMessageDelayed(START_VIDEO,
                                        seekKeySleepTime);
                            }
                            return true;
                        case Constant.Control_KEYCODE_OK:
                            if (!isShow) {
                                showMsg();
                            }
                            int runIng = (int) ((SystemClock.elapsedRealtime() - startTime
                                    .getBase())) / 1000;
                            int runMax = (int) ((SystemClock.elapsedRealtime() - endTime
                                    .getBase())) / 1000;
                            if (runIng >= runMax) {//重播
                                return true;
                            }
                            if (isPlayCompletion) {
                                pauseTime = 10;
                                handler.sendEmptyMessageDelayed(FIRST_PLAY, 30);
                                return true;
                            }

                            if (!isUserPause) {
                                isUserPause = true;
                                // playB.setVisibility(View.VISIBLE);
                                epg_control_bottom_pause.setVisibility(View.VISIBLE);
                                pause();
                                handler.sendEmptyMessageDelayed(REMOVE_MSG, 600);
                            } else {
                                isUserPause = false;
                                epg_control_bottom_pause.setVisibility(View.GONE);
                                // playB.setVisibility(View.INVISIBLE);
                                start();
                                handler.sendEmptyMessageDelayed(CLOSE_MSGV,
                                        2500);
                            }
                            return true;
                        case Constant.Control_KEYCODE_EXIT:
                            exitPlayer();
                            return true;
                        case Constant.Control_KEYCODE_MENU:
                            Log.i(TAG, "onKey: 点击了菜单");
                            lincon.setVisibility(View.VISIBLE);
                            playB.clearFocus();
                            makeFocus(lincon);
                            handler.sendEmptyMessageDelayed(CONNECT_EXIT, 6000);
                            return true;
                        default:
                            break;
                    }
                }
                return false;
            }
        });

        playB.setNextFocusRightId(R.id.ib_player_playforepg_control_play);
        playB.setNextFocusLeftId(R.id.ib_player_playforepg_control_play);
        playB.setNextFocusUpId(R.id.ib_player_playforepg_control_play);


        lincon.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    switch (keyCode) {
                        case Constant.Control_KEYCODE_OK:
                            connectProgram();
                            break;
                        case Constant.Control_KEYCODE_EXIT:
                            handler.sendEmptyMessageDelayed(CONNECT_EXIT, 1000);
                            break;
                        default:
                            break;
                    }

                }
                return false;
            }
        });
        lincon.setNextFocusRightId(R.id.lin_con);
        lincon.setNextFocusLeftId(R.id.lin_con);
        lincon.setNextFocusUpId(R.id.lin_con);

        startTime.setOnChronometerTickListener(new OnChronometerTickListener() {

            @Override
            public void onChronometerTick(Chronometer chronometer) {
                int runIng = (int) ((SystemClock.elapsedRealtime() - chronometer
                        .getBase())) / 1000;
                cm_playcontrol_starttime_tv.setText(getDrationTime(runIng));
                if ((seekB.getMax() - runIng) == 15) {
                    showMsg();

                }
                if ((seekB.getMax() - runIng) < 15) {
                    handler.removeMessages(CLOSE_MSGV);
                }
                if (runIng >= seekB.getMax() && isPlaying) {
                    exitPlayer();
                }

                if (!isUserPause) {
                    seekB.setProgress(runIng);
                }

            }
        });

    }

    private void connectProgram() {
        if (program != null) {
             localConnect();
        } else {
            showMsg("该节目不存在，收藏节目失败！！！", 2, true);
            handler.sendEmptyMessageDelayed(CONNECT_EXIT, 1000);
        }
    }

    private void  localConnect() {
        if ("1".equals(isConnect)) {
            isConnect="0";
            PlayObserveble.getInstance().connectProgram(0);
            Log.i(TAG, "localConnect: 取消收藏");
        } else {
            isConnect="1";
            PlayObserveble.getInstance().connectProgram(1);
            Log.i(TAG, "localConnect: 添加收藏");
        }
        setConnectState(isConnect);
        handler.sendEmptyMessageDelayed(CONNECT_EXIT, 1000);
    }
    private void  setConnectState(String fav){
        if ("1".equals(fav)){
            connect_logo.setImageResource(R.mipmap.icon_con);
            connect_text.setText(mContext.getResources().getText(R.string.program_connected));
        }else {
            connect_logo.setImageResource(R.mipmap.icon_con_dis);
            connect_text.setText(mContext.getResources().getText(R.string.program_unconnected));
        }
    }


    private String playLink = "";
    private Boolean changeurl = false;


    public void showMsg() {
        handler.removeMessages(CLOSE_MSGV);

        if (getActivity() == null) {
            return;
        }

        if (epgName != null) {
            epgName.setStart(true);
            epgName.setEllipsize(TextUtils.TruncateAt.valueOf("MARQUEE"));
        }
        if (peShowTopMsg == null) {
            Resources resources = getActivity().getResources();
            float upHeight = resources
                    .getDimension(R.dimen.player_control_heght);

            if (play_epg_top != null) {
                peShowTopMsg = ObjectAnimator.ofFloat(play_epg_top,
                        "translationY", -upHeight, 0);
            }

            peShowTopMsg.setDuration(500);
        }

        if (peShowBottomMsg == null) {
            Resources resources = getActivity().getResources();
            float upHeight = resources
                    .getDimension(R.dimen.player_control_heght);

            if (play_epg_bottom != null) {
                peShowBottomMsg = ObjectAnimator.ofFloat(play_epg_bottom,
                        "translationY", upHeight, 0);
            }

            peShowBottomMsg.setDuration(500);
        }

        if (peShowTopMsg.isRunning()) {
            return;
        }

        if (peShowBottomMsg.isRunning()) {
            return;
        }

        peShowBottomMsg.addListener(new AnimatorListener() {

            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                makeFocus(playB);
                handler.sendEmptyMessageDelayed(CLOSE_MSGV, 2500);
                isShow = true;

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }
        });
        // layout.setVisibility(View.VISIBLE);
        play_epg_top.setVisibility(View.VISIBLE);
        play_epg_bottom.setVisibility(View.VISIBLE);

        makeFocus(playB);
        peShowTopMsg.start();
        peShowBottomMsg.start();
    }

    public void closeMsg() {
        /*
         *
		 */
        if (epgName != null) {
            epgName.setStart(true);
            epgName.setEllipsize(TextUtils.TruncateAt.valueOf("END"));
        }
        if (peShowTopMsg != null && peShowTopMsg.isRunning()) {
            peShowTopMsg.cancel();
        }
        if (peShowBottomMsg != null && peShowBottomMsg.isRunning()) {
            peShowBottomMsg.cancel();
        }

        if (peShowBottomMsg != null) {
            peShowBottomMsg.reverse();
            peShowBottomMsg = null;
        }
        if (peShowTopMsg != null) {
            peShowTopMsg.reverse();
            peShowTopMsg.addListener(new AnimatorListener() {

                @Override
                public void onAnimationStart(Animator animation) {
                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    isShow = false;

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }
            });

            peShowTopMsg = null;
        } else {
            // layout.setVisibility(View.INVISIBLE);
            play_epg_top.setVisibility(View.INVISIBLE);
            play_epg_bottom.setVisibility(View.INVISIBLE);
        }

        isShow = false;

    }

    private boolean isRecodeShowMsg = false;

    public void recodeShowMsg(boolean isRecodeShowMsg) {
        this.isRecodeShowMsg = isRecodeShowMsg;
    }

    public boolean isRecodeShowMsg() {
        return isRecodeShowMsg;
    }

    public void play(String id, String name) {
        closeMsg();
        epg_bg.setVisibility(View.VISIBLE);
        // 在切换epg时，上一个epg的checkUpdate()延时消息还没执行。为了不出现两个乃至多个循环，多remove几次，没坏处。
        handler.removeMessages(CHECK_AND_SET_VIDEO_PROGRESS);
        handler.removeMessages(CHECK_AND_SET_VIDEO_PROGRESS);
        handler.removeMessages(CHECK_AND_SET_VIDEO_PROGRESS);
        backIsSave = false;
        isUserPause = true;
        // this.redayPlayEpg = epg;
        // this.readyPlayTv = tv;
        // handler.sendEmptyMessage(QUERY_COLLECT);
        epgName.setText(name);
        // closeMsg();
        // pause();
        stopPlay();
        if (!("-1".equals(progress) || "-2".equals(progress))) {//播放记录进来
            pauseTime = Long.parseLong("String") * 1000;
        }
        seekB.setSecondaryProgress(0);
        /*
         * if(layout != null){ initPlayControlLogic(); makeFocus(playB);
		 * handler.sendEmptyMessage(QUERY_COLLECT); }
		 */
        getEpgPathAndPlay(id);

    }

    // YG
    private void getEpgPathAndPlay(String id) {
        epg_control_bottom_pause.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.VISIBLE);
        showMsg();
        handler.sendEmptyMessageDelayed(REMOVE_MSG, 600);
        if (mSubscriber != null) {
            if (!mSubscriber.isUnsubscribed()) {
                mSubscriber.unsubscribe();
            }
        }
        mSubscriber = new Subscriber<MediaPlayList>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "请求错误" + e.getMessage());
                if (PolyManager.POLY_FAILD.equals(e.getMessage())) { // 接口错误，如：ret != 0
//                    String ret = e.getCause().getMessage();
                    String desc = e.getCause().getCause().getMessage();
                    showMsg(desc, 2, true);
                } else { // OKHTTP 错误
                    showMsg("该节目暂时无法播放，去看看其他节目吧。", 2, true);
                }
                isPlaying = false;
                mProgressBar.setVisibility(View.INVISIBLE);
                stopPlay();
                error();
            }

            @Override
            public void onNext(MediaPlayList mediaPlayList) {
                if (mediaPlayList != null) {
                    program = mediaPlayList;
                    setConnectState(isConnect);
                    if (mediaPlayList.getList() != null && mediaPlayList.getList().size() > 0) {
                        int size = (mediaPlayList.getList().size() - 1);
                        playLink = mediaPlayList.getList().get(size).getPlayLink();
                        Log.i(TAG, "onNext: " + playLink);
                        videoView.setURL(playLink);

                        //1.16
//                        playLink = "http://192.168.3.24:8112/HLS/a7b9eae751ff4846a22164f8631fc0be/index.m3u8";
                        //1.31.38
//                        playLink = "http://192.168.3.24:8112/HLS/c54b07d1e9284d8fbc49240676cdfaa4/index.m3u8";
//                        videoView.setURL(playLink);
                    } else {
                        showMsg("该节目暂时无法播放，去看看其他节目吧。", 2, true);
                        error();
                    }
                } else {
                    showMsg("该节目暂时无法播放，去看看其他节目吧。", 2, true);
                    error();
                }
            }
        };
        mPolyManager.getHealthyVodMediaPlayList(id, mSubscriber).subscribe(mSubscriber);
    }


    private void error() {
        Log.i(TAG, "error: 播放结束");
        cm_playcontrol_starttime_tv.setText("00:00:00");
        cm_playcontrol_endtime_tv.setText("00:00:00");
        epg_bg.setVisibility(View.VISIBLE);
        showMsg();
        handler.sendEmptyMessageDelayed(REMOVE_MSG, 600);
    }

    public static String msgError = "暂时不能播放 ";

    // 在快进的时候，因为线程会等待一会，如果快进的过快。seekBar到底后会重新返回0，再次来过。
    private boolean isPlayCompletion = false;

    private float perSecondWidth;

    private void initcontrol(MediaPlayer mp) {
        seekB.setMax((mp.getDuration() / 1000));
        endTime.setBase(SystemClock.elapsedRealtime() - mp.getDuration());
        cm_playcontrol_endtime_tv
                .setText(getDrationTime(mp.getDuration() / 1000));
        startTime.setBase(SystemClock.elapsedRealtime());
        startTime.start();
        perSecondWidth = (float) seekB.getWidth() / (float) seekB.getMax();
    }

    public void start() {
        ispause = false;
        pause_duration = pause_duration + (System.currentTimeMillis() - pause_time);
        Log.d(TAG, "暂停时长" + pause_duration);
        handler.removeMessages(SHOW_AD);
        handler.sendEmptyMessageDelayed(REMOVEAD, 500);
        videoView.start();
        if (pauseTime != 0) {
            startTime.setBase(SystemClock.elapsedRealtime() - pauseTime);
        } else {
            startTime.setBase(SystemClock.elapsedRealtime());
        }
        // isMePause = false;
        epg_control_bottom_pause.setBackgroundDrawable(getActivity()
                .getResources()
                .getDrawable(R.mipmap.player_control_pasue));
        startTime.start();
    }

    ;

    public long pauseTime = 10;
    //用于信息采集判断是否是用户暂停
    private Boolean ispause = false;

    public void pause() {
        ispause = true;
        pause_time = System.currentTimeMillis();
        Log.d(TAG, "暂停时刻" + pause_time);
        handler.removeMessages(SHOW_AD);
        handler.sendEmptyMessageDelayed(SHOW_AD, 300);
        // handler.removeMessages(CLOSE_MSGV);
        mProgressBar.setVisibility(View.INVISIBLE);
        epg_control_bottom_pause.setBackgroundDrawable(getActivity()
                .getResources()
                .getDrawable(R.mipmap.player_control_play));
        videoView.pause();
        if (seekB != null) {
            pauseTime = seekB.getProgress() * 1000;
        }

        if (startTime != null) {
            startTime.stop();
        }

    }

    public void pauseForFirst() {
        // handler.removeMessages(CLOSE_MSGV);
        mProgressBar.setVisibility(View.INVISIBLE);
        epg_control_bottom_pause.setBackgroundDrawable(getActivity()
                .getResources()
                .getDrawable(R.mipmap.player_control_play));
        videoView.pause();
        if (startTime != null) {
            startTime.stop();
        }
    }

    public void startForFirst() {
        videoView.start();
        epg_control_bottom_pause.setBackgroundDrawable(getActivity()
                .getResources()
                .getDrawable(R.mipmap.player_control_pasue));
        startTime.start();
    }

    private String videoid;
    private String videoname;
    private String progress;
    private String isConnect;
    public void readyPlayEpgSingle(String id, String name, String progress,String isConnect) {
        this.videoid = id;
        this.videoname = name;
        this.progress = progress;
        this.isConnect=isConnect;
    }


    private boolean backIsSave;

    private void makeFocus(View view) {
        if (view != null) {
            view.requestFocus();
            view.requestFocusFromTouch();

            view.setFocusable(true);
            view.setFocusableInTouchMode(true);
        }
    }

    public boolean isShow() {
        return isShow;
    }

    @Override
    public void onDestroy() {
        if (ispause) {
            pause_duration = pause_duration + (System.currentTimeMillis() - pause_time);
            Log.i(TAG, "暂停下退出" + pause_duration);
            int duration = (int) (((System.currentTimeMillis() - currentHealth) - pause_duration) / 1000);
            Log.i(TAG, "观看时长：" + duration);
        }
        //       Log.i(TAG, "onDestroy: "+videoView.getVideo().getCurrentPosition());
        //       Log.i(TAG, "onDestroy: "+videoView.getVideo().getDuration());
        //     Log.i(TAG, "onDestroy: "+"--------------------------------");
//            PlayObserveble.getInstance().programHis(seekB.getProgress());
//        } else {
//            PlayObserveble.getInstance().programHis(-2);
//        }
        OperateVideoView.getInstance().unListener();
        stopPlay();
        super.onDestroy();
    }


    public void stopPlay() {
        if (videoView != null) {
            videoView.terminate();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // pause();
    }

    @Override
    public void onStop() {
        handler.removeMessages(DELAYPLAY);
        handler.removeMessages(PLAYERROR);
        videoView.unRegisteResever(getActivity());

        if (!backIsSave) {
            if (seekB != null) {
                // 袁刚
                // mPlayEpg.setBreakPoint(seekB.getProgress() + "");
            }
        }
        super.onStop();
    }


    public static final int UPDATE_PF_EPG = 0x001;

    public static final int CLOSE_MSGV = 0x002;

    public static final int CHECK_AND_SET_VIDEO_PROGRESS = 0x003;

    public static final int START_VIDEO = 0x004;

    public static final int BREAKPOINT_START_VIDEO = 0x006;

    public static final int VIDEO_IS_BUFFERING = 0x007;

    public static final int VIDEO_IS_PLAY = 0x008;

    public static final int FIRST_PLAY = 0x009;

    public static final int REMOVE_MSG = 0x0010;

    public static final int CLOSE_MSGV2 = 0x0013;

    public static final int SHOW_AD = 0x0014;

    public static final int DELAYPLAY = 0x0016;

    public static final int REMOVEAD = 0x0017;

    public static final int PLAYERROR = 0x0018;

    public static final int CONNECT_EXIT = 0x0019;

    private Handler handler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case VIDEO_IS_BUFFERING:
                    startTime.stop();
                    break;
                case VIDEO_IS_PLAY:
                    if (isUserPause) {
                        startTime.stop();
                        videoView.pause();
                        epg_control_bottom_pause
                                .setBackgroundDrawable(getActivity()
                                        .getResources()
                                        .getDrawable(
                                                R.mipmap.player_control_play));
                    } else {
                        epg_control_bottom_pause
                                .setBackgroundDrawable(getActivity()
                                        .getResources()
                                        .getDrawable(
                                                R.mipmap.player_control_pasue));
                    }
                    break;
                case UPDATE_PF_EPG:
                    break;
                case CLOSE_MSGV:
                    closeMsg();
                    break;
                case REMOVE_MSG:
                    handler.removeMessages(CLOSE_MSGV);
                    break;
                case CHECK_AND_SET_VIDEO_PROGRESS:
                    // if(!Constant.PLAY_EPG_MSG_TV){
                    // setVideoProgress(null);
                    // }
                    handler.removeMessages(CHECK_AND_SET_VIDEO_PROGRESS);
                    /*
                     * if(isCheck){ checkUpdate();
					 * handler.sendEmptyMessageDelayed
					 * (CHECK_AND_SET_VIDEO_PROGRESS, 800); }
					 */
                    break;
                case START_VIDEO:
                    if (isPlayCompletion) {
                        return;
                    }
                    seekB.setProgress(seekB.getSecondaryProgress());
                    videoView.seekTo(seekB.getProgress() * 1000);
                    isSeekTo = true;
                    if (pop != null && pop.isShowing()) {
                        pop.dismiss();
                    }
                    // if(isUserPause){
                    // startTime.stop();
                    // videoView.pause();
                    // return;
                    // }
                    isUserPause = false;
                    if (seekB.getProgress() <= seekB.getMax()) {
                        if (istimestop) {
                            startTime.start();
                            videoView.start();
                        }
                        istimestop = true;
                        if (!isUserPause) {
                            // start();
                            // if(!videoView.getVideo().isPlaying()){
                            // videoView.start();
                            // }
                            // isMePause = false;
                            epg_control_bottom_pause
                                    .setBackgroundDrawable(getActivity()
                                            .getResources()
                                            .getDrawable(
                                                    R.mipmap.player_control_pasue));
                        }
                    }
                    break;
                case BREAKPOINT_START_VIDEO:
                    if (isPlayCompletion) {
                        return;
                    }
                    seekB.setSecondaryProgress((int) (pauseTime / 1000));
                    seekB.setProgress(seekB.getSecondaryProgress());
                    videoView.seekTo(seekB.getSecondaryProgress() * 1000);
                    isUserPause = false;
                    isSeekTo = true;
                    if (seekB.getProgress() <= seekB.getMax()) {
                        startTime.start();
                        if (!isUserPause) {
                            if (!videoView.getVideo().isPlaying()) {
                                videoView.start();
                            }
                            // isMePause = false;

                            // isinit = true;
                            handler.sendEmptyMessageDelayed(
                                    CHECK_AND_SET_VIDEO_PROGRESS, 100);
                        }
                    }
                    break;
                case FIRST_PLAY:
                    play(videoid, videoname);
                    break;
                case CLOSE_MSGV2:
                    closeMsg();
                    break;
                case DELAYPLAY:
                    startTime.stop();
                    // 发一个延时的handle，并判断，onprepar里面的标记，到延时标记没变就提示错误，变了就不做处理。
                    Log.d(TAG, "进入延时播放");
                    plays = true;
                    pauseTime = seekB.getProgress() * 1000;
                    reset();
                    stopPlay();
                    getEpgPathAndPlay(videoid);
                    // handler.sendEmptyMessage(DOWNLOAD);
                    break;
                case PLAYERROR:
                    Log.d(TAG, "缓冲重播25s无响应");
                    reset();
                    stopPlay();
                    startTime.stop();
                    mProgressBar.setVisibility(View.INVISIBLE);
                    error();
                    break;
                case CONNECT_EXIT:
                    lincon.clearFocus();
                    lincon.setVisibility(View.GONE);
                    makeFocus(playB);
                    break;
                default:
                    break;
            }
        }
    };
    private boolean plays = false;

    private ObjectAnimator peShowTopMsg;

    private ObjectAnimator peShowBottomMsg;


    /**
     * 得到当前时间
     */
    public String getDrationTime(int duration) {
        String durationTime = "";

        int h = duration / 3600;
        if (h < 10) {
            durationTime += "0" + h + ":";
        } else {
            durationTime += h + ":";
        }

        int m = duration % 3600 / 60;// 分钟数
        if (m < 10) {
            durationTime += "0" + m + ":";
        } else {
            durationTime += m + ":";
        }
        duration = duration % 60;
        int s = duration; // 秒数
        if (s < 10) {
            durationTime += "0" + s;
        } else {
            durationTime += s;
        }
        return durationTime;
    }

    private void setPop(String text, View v, int secondPro) {
        if (pop != null && pop.isShowing()) {// 如果当前正在显示，则将被处理
            pop.dismiss();
        }
        if (pop == null) {
            pop = new PopupWindow(pop_playTime, LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
        }
        pop_playTime.setText(text);
        pop_playTime.invalidate();
        pop.showAsDropDown(v,
                (int) (secondPro * perSecondWidth) - pop.getWidth() / 2 - 85,
                -(v.getHeight() + pop.getHeight() + popLowerY));
    }

    private void updatePop(String text, View v, int secondPro) {
        if (pop == null) {
            pop = new PopupWindow(pop_playTime, LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
        }
        int popX = (int) (secondPro * perSecondWidth) - pop.getWidth() / 2 - 85;
        pop_playTime.setText(text);
        pop_playTime.invalidate();
        pop.update(v, popX, -(v.getHeight() + pop.getHeight() + popLowerY),
                pop.getWidth(), pop.getHeight());
    }

    private void reset() {
        if (startTime != null) {
            startTime.setBase(SystemClock.elapsedRealtime());
            startTime.stop();
        }
        isPlayCompletion = true;
        isPlaying = false;
        handler.removeMessages(CHECK_AND_SET_VIDEO_PROGRESS);
        backIsSave = false;
        isUserPause = true;
        videoView.reset();
        seekB.setProgress(0);
        seekB.setSecondaryProgress(0);
    }

    private void playvideo() {
        playB.requestFocus();
        handler.sendEmptyMessageDelayed(CLOSE_MSGV2, 2500);
        Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.gradually);
        epg_bg.startAnimation(animation);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                epg_bg.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        isUserPause = false;
        startForFirst();
    }

    private void exitPlayer() {
        startTime.stop();
        backIsSave = true;
        if (!isPlayCompletion) {
            Log.i(TAG, "exitPlayer: " + seekB.getProgress());
            PlayObserveble.getInstance().programHis(seekB.getProgress(),0);
        } else {
            PlayObserveble.getInstance().programHis(-2,-1);
        }
        reset();
        stopPlay();
        getActivity().finish();
    }

    private CommonDialog CommonDialog;

    private void showMsg(String msg, int type, final Boolean isFinish) {
        if (CommonDialog == null) {
            CommonDialog = new CommonDialog(mContext);
        }

        CommonDialog.setContent(msg, type);
        CommonDialog.getLeftBtn().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                CommonDialog.dismiss();
                if (isFinish) {
                    exitPlayer();
                }
            }
        });
        CommonDialog.setCancelable(false);
        if (!getActivity().isFinishing()) {
            CommonDialog.show();
        }
    }


}
